package com.djsearch.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

import com.djsearch.R;
import com.djsearch.adapter.GroupShopListViewAdapter;
import com.djsearch.adapter.TaoGouListViewAdapter;
import com.djsearch.bean.ForPurchase;
import com.djsearch.bean.GroupBuyGoods;
import com.djsearch.controller.AsyncHandler;
import com.djsearch.controller.IRequest;
import com.djsearch.controller.IResponse;
import com.djsearch.controller.JSONReq;
import com.djsearch.controller.JSONResp;
import com.djsearch.ui.GroupShopActivity.RequestParamStruct;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

/**
 * 淘购页面
 * @author chenyang2
 *
 */
public class TaoGouActivity extends BaseActivity{
	
	private Context mContext;
	private Button bacButton;
	private ListView goodsListView;
	private RelativeLayout sortLayout,paixuLayout;
	private int PAGE = 1;//当前显示到第几页数据
	private List<ForPurchase> nextPageGoodsList;//存放下一页请求的新数据
	private List<ForPurchase> taoGouShopList;//存放当前页面数据
	private TaoGouListViewAdapter taoGouListViewAdapter;
	private List<SortBean> sortBeanList;
	private TextView groupShopText;//产品类别
	private RelativeLayout taoGouTopTitle, editLayout, layout;
	private EditText searchEdit;
	private ImageView searchImg;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.taogou_layout);
		mContext = this;
		sortBeanList = new ArrayList<SortBean>();//分类数据
		nextPageGoodsList = new ArrayList<ForPurchase>(); //更多（下一页数据）
		taoGouShopList = new ArrayList<ForPurchase>(); //更多（下一页数据）
		//初始化主界面
		initView();
		//初始化主界面相关点击事件
		initOnClick();
		//
		initHandler();
	}

	@Override
	void initHandler() {
		// TODO Auto-generated method stub
		
	}

	@Override
	void initView() {
		taoGouTopTitle = (RelativeLayout)findViewById(R.id.taoGouTopTitle);
		editLayout = (RelativeLayout)findViewById(R.id.editLayout);
		searchEdit = (EditText)findViewById(R.id.init_name);
		searchImg = (ImageView)findViewById(R.id.searchImg);
		layout = (RelativeLayout)findViewById(R.id.layout);
		taoGouListViewAdapter = new TaoGouListViewAdapter(mContext,taoGouShopList);
		bacButton = (Button)findViewById(R.id.taoGouBackBtn);
		goodsListView = (ListView)findViewById(R.id.taoGouListView);
		goodsListView.setAdapter(taoGouListViewAdapter);
		sortLayout = (RelativeLayout)findViewById(R.id.sortLayout);
		groupShopText = (TextView)findViewById(R.id.groupShopText);
//		paixuLayout = (RelativeLayout)findViewById(R.id.paixuLayout);
//		requestGoodsData(initRequestMap());
		requestSortData();
		
	}

	@Override
	void initOnClick() {
		bacButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startActivity(mContext, MainActivity.class, 1);
				
			}
		});
		
		goodsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				startActivity(mContext, TaoGouDetailsActivity.class, 0, taoGouShopList.get(position));
			}
		});
		sortLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showSearchWayPopupWindow(v, goodsListView.getHeight(), -getWidth()/2);
				
			}
		});
		setOnRequestDataListner(new RequestDataListner(){
			public void requestData(int position) {
				// TODO Auto-generated method stub
				groupShopText.setText(sortList.get(position));
				RequestParamStruct.page = 1;
				PAGE = 1;
				taoGouShopList.clear();//选择不同的分类时，将当前的分类数据清空
				RequestParamStruct.queryByType = sortBeanList.get(position).getCid();
				requestGoodsData(initRequestMap());
			}
		});
		
		/**
		 * 滑动到底部自动加载功能
		 */
		goodsListView.setOnScrollListener(new AbsListView.OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				if ( scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
					if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
					        RequestParamStruct.page = PAGE;
					        requestGoodsData(initRequestMap());
					}
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				
			}
		});
		
		searchImg.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (searchEdit.getText().toString().equals("")) {
					startAnimation(searchEdit);
				} else {
					//请求数据
				}
			}
		});
	}
	
	/**
	 * 请求服务器数据方法
	 */
	private void requestGoodsData(Map<String, String> map) {
		IRequest request = new JSONReq("taogou",map);
		
		HTTP.post(request, new AsyncHandler(){
			@Override
			public void onStart() {
				showDialog("正在加载...");
				if (PAGE == 1) {
					goodsListView.setVisibility(View.GONE);
				}
			}
			/**
			 * {"shopName":"*【品牌特卖】※真维斯 正品男装修身型牛仔裤381501原价160",
			 * "description":"*【品牌特卖】※真维斯 正品男装修身型牛仔裤381501原价160",
			 * "shopUrl":"http:\/\/item.tbsandbox.com\/item.htm?id=1500006950787",
			 * "hasBuy":"17",
			 * "smallImage":"http:\/\/img04.taobaocdn.com\/bao\/uploaded\/i4\/T1MR_PXoVdXXciGVbX_114034.jpg_b.jpg","salePrice":"49.0","nowPrice":"",
			 * "bigImage":"http:\/\/img04.taobaocdn.com\/bao\/uploaded\/i4\/T1MR_PXoVdXXciGVbX_114034.jpg_b.jpg","sale":""}
			 */
			@Override
			public void onSuccess(JSONResp response) {
				// TODO Auto-generated method stub
				int result = response.result();
				if(IResponse.Success==result){
					 ++PAGE;
					 getDataToResolve(response);
					 goodsListView.setVisibility(View.VISIBLE);
					 Toast.makeText(mContext, "成功"+PAGE, 5000).show();
					   
				} else if (IResponse.Fail==result) {
					//返回数据失败
					Toast.makeText(mContext, "失败", 5000).show();
				}
					missDialog();
			}
			@Override
			public void onFailure(Throwable e, String response) {
				// TODO Auto-generated method stub
//				super.onFailure(e, response);
				missDialog();
//				Log.e("GROUP", response);
				Toast.makeText(mContext, response, 5000).show();
			}
			
		});
	}
	
	/**
	 * 请求分类数据
	 */
	private void requestSortData() {

		IRequest request = new JSONReq("taogou_sort");
		HTTP.post(request, new AsyncHandler(){
			@Override
			public void onStart() {
				showDialog("正在加载...");
				
			}
			
			@Override
			public void onSuccess(JSONResp response) {
				// TODO Auto-generated method stub
				int result = response.result();
				if(IResponse.Success==result){
					    getSortDataToResolve(response);
//					    getHeight()-taoGouTopTitle.getHeight()-
//			    		editLayout.getHeight()
					    showSearchWayPopupWindow(sortLayout,  getHeight()*2/3
//					    		editLayout.getHeight()
					    		, -getWidth()/2);
						Toast.makeText(mContext, "成功", 5000).show();
						Log.e("response", response.toString());
				} else if (IResponse.Fail==result) {
					Toast.makeText(mContext, "失败", 5000).show();
				}
					missDialog();
//				    missProgressBar();
			}
			@Override
			public void onFailure(Throwable e, String response) {
				// TODO Auto-generated method stub
//				super.onFailure(e, response);
				missDialog();
//				Log.e("GROUP", response);
//				Toast.makeText(mContext, response, 5000).show();
//				missProgressBar();
			}
			
		});
	
		
	}
	
	/**
	 * 请求数据 data参数数据实体类
	 * 当请求条件变化时，相应赋予该实体类的属性值
	 * {“queryByName”:”裤子”,”queryByOrder”:”2”,queryByType:”1”,”page”:”1”,”pageNum”:”10”}
	 *
	 */
	 static class RequestParamStruct{
	 static	String queryByName = "";//商品名称，为空时是请求所有团购商品
	 static String queryByType = " ";//
	 static String queryByOrder = " ";//团购排序
	 static int page = 1;//页码
	 static String pageNum = "10";//一页显示的数据条数 
	}
	
	 private Map<String, String> initRequestMap() {
			Map<String, String> map = new HashMap<String, String>();
			map.put("queryByName", RequestParamStruct.queryByName);//商品名称
			map.put("queryByType", RequestParamStruct.queryByType);//
			map.put("queryByOrder", RequestParamStruct.queryByOrder);//
			map.put("page", String.valueOf(RequestParamStruct.page));//页码
			map.put("pageNum", RequestParamStruct.pageNum);//一页显示的数据条数
			return map;
		}
	
	/**
	 * 点击返回键
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			startActivity(mContext, MainActivity.class, 1);
		}
		return false;
		
	}

	/**
	 * 收到分类数据时去处理
	 * @param response
	 */
	private void getSortDataToResolve(JSONResp response) {
		
		try {
			JSONArray jsonArray;
			jsonArray = response.getJSONArray("returnMessage");
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject obJsonObject = jsonArray.getJSONObject(i);
				SortBean sortBean = new SortBean();
				sortBean.setSortName(obJsonObject.getString("name"));
				sortBean.setCid(obJsonObject.getString("cid"));
				if (obJsonObject.getString("isParent").equals("false")) {
					sortBean.setParent(false);
				} else {
					sortBean.setParent(true);
				}
				sortBeanList.add(sortBean);
			}
//			Gson gson = new Gson();   
//	        Type type = new TypeToken<List<SortBean>>(){}.getType();  //指定集合对象属性  
//	        List<SortBean> fromJson = gson.fromJson(response.getString("returnMessage"), type);
//			sortBeanList.addAll(fromJson);
		} catch (JsonSyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			for (int i=0;i<sortBeanList.size();i++ ) {
				if (!sortBeanList.get(i).isParent()) {
					sortList.add(sortBeanList.get(i).getSortName());
				}
			}
			sortPopuWindowAdapter.refreshData(sortList);
		}
		
	
	}
	
	@Override
	void getDataToResolve(JSONResp response) {
		

		// TODO Auto-generated method stub
		try {
			Gson gson = new Gson();   
	        Type type = new TypeToken<List<ForPurchase>>(){}.getType();  //指定集合对象属性  
	        List<ForPurchase> fromJson = gson.fromJson(response.getString("returnMessage"), type); 
	        nextPageGoodsList.addAll(fromJson);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (nextPageGoodsList.size() == 0) {
				//当没有更多的数据了处理
			} else {
				taoGouShopList.addAll(nextPageGoodsList);
				nextPageGoodsList.clear();
			}
			taoGouListViewAdapter.refreshData(taoGouShopList);
		}
	}
	/**
	 * 分类实体类 
	 * @author chenyang2
	 *
	 */
	 class SortBean {
		 String cid;//分类编号；
		 String sortName;//分类的名字
		 boolean isParent;//分类是否为父分类
		 
		public String getCid() {
			return cid;
		}
		public void setCid(String cid) {
			this.cid = cid;
		}
		public String getSortName() {
			return sortName;
		}
		public void setSortName(String sortName) {
			this.sortName = sortName;
		}
		
		public boolean isParent() {
			return isParent;
		}
		public void setParent(boolean isParent) {
			this.isParent = isParent;
		}
		
	}

}
